/*
 * @Author: gyc
 * @Date: 2020-06-19 13:36:49
 * @LastEditTime: 2020-08-25 09:23:37
 * @Description: Nuxt测试版
 */
'use strict';
const room = 'default_room';

module.exports = () => {
    return async (ctx, next) => {
        const {
            app
        } = ctx
        const userid = ctx.socket.handshake.query.userid;
        const nsp = ctx.app.io.of('/');
        // const iuser = await app.redis.get(user)
        nsp.to(room).emit('online', {
            msg: 'welcome',
            id: ctx.socket.id
        });
        nsp.adapter.clients(['default_room'], (err, clients) => {
            console.log(clients, 'da'); // 一个包含所有连接上的客户端id的数组
            nsp.to(room).emit('online', {
                msg: 'welcome 2',
            });
        });
        //  app.redis.set(user, ctx.socket.id)
        const hasRoom = await app.redis.get(userid)
        console.log(hasRoom, '111')
        // ctx.socket.emit(id, msg);
        ctx.socket.join(room);
        if (hasRoom) {
            console.log('1')
            app.redis.set(userid, ctx.socket.id)
            await nsp.adapter.remoteDisconnect(hasRoom, true, err => {});
        } else {
            app.redis.set(userid, ctx.socket.id)
        }



        // const query = ctx.socket.handshake.query;
        await next();
        ctx.socket.leave(room);
        nsp.to(room).emit('online', {
            msg: 'bye bye',
            id: ctx.socket.id
        });
        console.log('disconnect!');
    };
};